package com.igeek.boot.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author fengqq
 * @Description 参数注解--响应重定向传递数据
 * @Date 2024/8/16  9:58
 *
 * 响应重定向传递数据:
 * 1.发送数据 redirectAttributes.addAttribute(key,value)+ "redirect:/path"  ==> /path?key=value
 * 2.接收数据 @RequestParam("key") String value
 */
@Controller
public class RedirectController {

    //发送数据
    @GetMapping("/sendRedirectData")
    public String sendRedirectData(
            HttpServletRequest request,
            Model model,
            RedirectAttributes redirectAttributes
    ){
        //添加数据 到 请求域 中
        request.setAttribute("request-a","aaa");
        model.addAttribute("model-b","bbb");

        //携带响应重定向的数据（数据追加在地址栏的后面） http://localhost:8084/getRedirectData?redirect-c=ccccc
        redirectAttributes.addAttribute("redirect-c","ccccc");

        //响应重定向 会产生新的请求 不会继续携带请求域中的数据
        return "redirect:/getRedirectData";
    }

    //接收数据
    @GetMapping("/getRedirectData")
    @ResponseBody
    public Map<String,Object> getRedirectData(
            @RequestParam("redirect-c") String c,
            @RequestAttribute(value = "request-a",required = false) String a,
            @RequestAttribute(value = "model-b",required = false) String b
    ){
        HashMap<String, Object> map = new HashMap<>();
        map.put("a",a);//null
        map.put("b",b);//null
        map.put("c",c);//ccccc
        return map;
    }
}
